<?php

class ControllerPublic extends ControllerBase {
    //region MENU

    protected function SetLanguagePicker(){
        parent::QuickNavigation($this->Fetch("ui_menu_language.tpl"));
    }

    protected function SetMenu(){
        $key = "menu";
        $this->Smarty->assign($key, $this->getMenu());
        parent::Navigation($this->Fetch("ui_menu.tpl"));
    }

    private function getMenu(){
        $items = $this->SetPages(0);

        if($this->Smarty->debugging){
            $debugInfo["menu"] = $items;
            $di["menu_DEBUG_INFO"][] = $debugInfo;
            echo "<pre>";
            print_r($di);
            echo "</pre>";
        }

        return $items;
    }

    private function SetPages($depth, $parentId = null){
        $output = null;
        if($depth < MENU_DEPTH){
            $input = $this->GetPages($parentId);
            $pageTypes = appcode\enum\PageType::GetArray();
            $depth++;
            $i = 0;
            foreach ($input as $value) {
                $pageId = $value["id"];
                $subPages = $this->SetPages($depth, $pageId);
                $output[$i]['id'] = $pageId;
                $output[$i]['linktitle'] = $value["linktitle"];
                $output[$i]['parent_id'] = $value["parent_id"];
                $output[$i]['controller'] =  $pageTypes[$value["pagetype_id"]];
                $output[$i]['action'] =  $value["action"];
                $output[$i]['subpages'] = $subPages;
                $output[$i]['selected'] = ($pageId == $this->Id);
                $output[$i]['childSelected'] = $this->IsChildSelected($subPages);
                $i++;
            }
        }
        return $output;
    }

    private function GetPages($parentId = null){
        $pages = Doctrine_Core::getTable('Page')
            ->createQuery('p')
            ->select("p.id, p.parent_id, p.linktitle, p.pagetype_id, p.action")
            ->where('p.visibility_id = '.appcode\enum\Visibility::GetByName(appcode\enum\Visibility::V_public).'  && p.showinmenu = 1 && p.language = "'.$this->Language.'" && p.parent_id '.(isset($parentId) ? ("= ".$parentId) : "is null"))
            ->orderBy("p.ordernumber")
            ->fetchArray();
        return $pages;
    }

    private function IsChildSelected($array){
        if(isset($array)){
            foreach ($array as $value) {
                if($value["id"] == $this->Id){
                    return true;
                }
            }
        }
        return false;
    }
}
